package pers.vic.base.web.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import pers.vic.base.tools.Tools;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;


/**
 * XSS过滤
 */
public class XssFilter implements Filter {
	
	private Logger logger = LoggerFactory.getLogger(XssFilter.class);
	
	private Set<String> excludeSet = new HashSet<String>(); 
	
    @Override
    public void init(FilterConfig config) throws ServletException {
    	logger.info("init XssFilter....................................");
    	String excludes = config.getInitParameter("excludes");
    	if(StringUtils.isNotEmpty(excludes)) {
    		String[] excludeUrls = excludes.split(",");
    		for(String url : excludeUrls) {
    			excludeSet.add(url);
    		}
    	}
    }
    
    private boolean isFilter(String url) {
    	for(String exclude : excludeSet){
    		if(url.startsWith(exclude)) {
    			return false;
    		}
    	}
    	return true;
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
    	String url = Tools.getRequestUrl((HttpServletRequest)request);
    	if("/".equals(url) || !isFilter(url)) {
    		chain.doFilter(request, response);
    		return;
    	}
    	logger.info("into XssFilter....................................");
    	
        XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper(
                (HttpServletRequest) request);
        chain.doFilter(xssRequest, response);
    }

    @Override
    public void destroy() {
    }

}